package cc.shacocloud.mirage.utils.collection;

import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;

/**
 * 自排序禁止重复集合，内部维护一个hash表来禁止重复，基于{@link SelfSortList} 实现
 *
 * @param <E> 泛型实例
 */
public class SelfSortSet<E, R> extends SelfSortList<E> {
    
    private final Function<E, R> repeatedConditionFunc;
    
    private final Set<R> repeatedSet = new HashSet<>();
    
    /**
     * @param comparable            获取当前对象排序所用值的函数
     * @param repeatedConditionFunc 重复条件函数，获取该对象的标识值，该用于唯一判断
     */
    public SelfSortSet(Comparable<E> comparable,
                       Function<E, R> repeatedConditionFunc) {
        this(DEFAULT_CAPACITY, comparable, repeatedConditionFunc);
    }
    
    public SelfSortSet(int initialCapacity,
                       Comparable<E> comparable,
                       Function<E, R> repeatedConditionFunc) {
        super(initialCapacity, comparable);
        this.repeatedConditionFunc = repeatedConditionFunc;
    }
    
    @Override
    public boolean add(E e) {
        R repeatVal = repeatedConditionFunc.apply(e);
        // 已经存在重复的数据 不保存
        if (repeatedSet.contains(repeatVal)) return false;
        repeatedSet.add(repeatVal);
        
        return super.add(e);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public boolean remove(Object o) {
        boolean remove = super.remove(o);
        if (remove) {
            R repeatVal = repeatedConditionFunc.apply((E) o);
            repeatedSet.remove(repeatVal);
        }
        return remove;
    }
    
}
